package Audio;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

import sun.audio.AudioPlayer;
import sun.audio.AudioStream;


/**
 * Clase Audio que controla la musica del juego.
 * @author Andres Garcia Amado, Federico Quattrocchio, Marias Lameiro.
 */
public class Audio {

    /** El reproductor de audio */
    protected AudioPlayer p;
    
    Clip clip;
    
    /** InputStream */
    protected InputStream in;
    
    protected AudioStream audio;
    
    /**
     * Reproduce la musica del juego
     *
     * @throws Exception
     */
    public void reproducir() throws Exception        
    {      
    	String sonido = "src/Audio/Hydrogen.wav";
        in = new FileInputStream(sonido);
        audio = new AudioStream(in);
        AudioPlayer.player.start(audio);
        
    }
    
    /**
     * Detener audio.
     */
    public void detenerAudio(){
    	AudioPlayer.player.stop(audio);
    }
    
    /**
     * Reproducir ganaste.
     *
     * @throws Exception the exception
     */
    public void reproducirGanaste() throws Exception{
    	String sonido = "src/Audio/Joe_Esposito_Youre_the_best.wav";       
        in = new FileInputStream(sonido);
        audio = new AudioStream(in);
        AudioPlayer.player.start(audio);
    }
    
    public void doPlay(final String url) {
        try {
        	InputStream audioSrc = getClass().getResourceAsStream(url);
        	//add buffer for mark/reset support
        	InputStream bufferedIn = new BufferedInputStream(audioSrc);
        	AudioInputStream audioStream = AudioSystem.getAudioInputStream(bufferedIn);
            stopPlay();
//            AudioInputStream inputStream = AudioSystem
//                    .getAudioInputStream(getClass().getResourceAsStream(url));
            clip = AudioSystem.getClip();
            clip.open(audioStream);
            clip.start();
        } catch (Exception e) {
            stopPlay();
            System.err.println(e.getMessage());
        }
    }

    public void stopPlay() {
        if (clip != null) {
            clip.stop();
            clip.close();
            clip = null;
        }
    }
}
